package com.epam.training.concurrency.second.task1;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Series {

	private final int threadNumber;
	private Queue<Future<Double>> threads;

	public Series(int threadNumber) {
		this.threadNumber = threadNumber;
		threads = new LinkedList<Future<Double>>();
	}

	public double calculateSeries(int limitSecond) throws InterruptedException,
			ExecutionException {

		Double sum = 0.0;

		ExecutorService es = Executors.newFixedThreadPool(5);

		int step = limitSecond / threadNumber;

		int i = 0;

		for (int j = 0; j < threadNumber; j++) {
			i += step;
			threads.offer(es.submit(new CalculateSerias(i)));
		}

		for (int j = 0; j < threadNumber; j++) {
			sum += threads.poll().get();
		}

		es.shutdown();

		return sum;
	}
}
